package com.my.app.tools.ui;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.my.app.tools.core.business.CoreBusiness;
import com.my.app.tools.pojo.em.cache.OcrService;
import com.my.app.tools.ui.awt.ScreenShotMainWindow;
import com.my.app.tools.util.AppThreadUtil;
import com.my.app.tools.util.LogUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.List;

/**
 * ui操作
 *
 * @author guochaohui
 * @return
 * @date 2020-03-16 10:17
 */
public class AppUiOcr {

    private static JPanel mainPanel;
    private static JPanel controlPanel;
    private static JButton screenShotButton;
    private static JButton ocrButton;
    private static JComboBox ocrServiceTypeComboBox;
    private static JCheckBox autoOcrCheckBox;

    private static JPanel imagePanel;
    private static JScrollPane imageScrollPane;
    private static JLabel imageLabel;

    private static JPanel ocrPanel;
    private static JScrollPane ocrScrollPane;
    private static JTextArea ocrText;

    /**
     * 初始化UI
     *
     * @return
     * @author guochaohui
     * @date 2020-03-16 10:20
     */
    public static final JPanel InitUi() {

        // 所有控件面板
        mainPanel = new JPanel(null);
        mainPanel.setBounds(0, 0, AppUiMain.appWindowWidth, AppUiMain.appWindowHeight);

        // 所有控件
        controlPanel = new JPanel(null);
        controlPanel.setBounds(10, 10, 610, 60);
        controlPanel.setBorder(BorderFactory.createTitledBorder("控制按钮"));

        screenShotButton = new JButton("屏幕截图");
        screenShotButton.setBounds(50, 22, 90, 20);
        screenShotButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                screenShot(false);
            }
        });
        controlPanel.add(screenShotButton);

        ocrButton = new JButton("识别文字");
        ocrButton.setBounds(180, 22, 90, 20);
        ocrButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                imageOcr(false);
            }
        });
        controlPanel.add(ocrButton);

        ocrServiceTypeComboBox = new JComboBox(CoreBusiness.ocrServiceType());
        ocrServiceTypeComboBox.setBounds(310, 22, 100, 20);
        controlPanel.add(ocrServiceTypeComboBox);

        autoOcrCheckBox = new JCheckBox("截图后自动识别", true);
        autoOcrCheckBox.setBounds(440, 22, 120, 20);
        controlPanel.add(autoOcrCheckBox);

        mainPanel.add(controlPanel);

        imagePanel = new JPanel(null);
        imagePanel.setBounds(10, 80, 320, 360);
        imagePanel.setBorder(BorderFactory.createTitledBorder("截图预览"));

        imageLabel = new JLabel();
        imageLabel.setBounds(10, 20, 300, 330);
        imageScrollPane = new JScrollPane(imageLabel);
        imageScrollPane.setBounds(10, 20, 300, 330);
        imagePanel.add(imageScrollPane);
        mainPanel.add(imagePanel);

        ocrPanel = new JPanel(null);
        ocrPanel.setBounds(340, 80, 280, 360);
        ocrPanel.setBorder(BorderFactory.createTitledBorder("识别结果"));

        ocrText = new JTextArea();
        ocrText.setBounds(10, 20, 260, 330);
        ocrText.setAutoscrolls(true);
        ocrText.setLineWrap(true);
        ocrScrollPane = new JScrollPane(ocrText);
        ocrScrollPane.setBounds(10, 20, 260, 330);
        ocrPanel.add(ocrScrollPane);
        mainPanel.add(ocrPanel);

        return mainPanel;
    }

    /**
     * 截图
     *
     * @return
     * @author guochaohui
     * @date 2020-04-01 16:52
     */
    public static void screenShot(boolean trayRun) {
        AppThreadUtil.INSTANCE.getExecutor().submit(() -> {
            try {
                AppUiMain.hideAppUi();
                Thread.sleep(200);

                GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
                GraphicsDevice[] graphicsDevices = graphicsEnvironment.getScreenDevices();
                if (graphicsDevices.length < 1) {
                    AppUiMain.errorMsgBox("没有检测到显示屏幕");
                    return;
                }
                List<ScreenShotMainWindow> screenShotWindows = Lists.newArrayList();
                for (GraphicsDevice device : graphicsDevices) {
                    //获取屏幕尺寸
                    Rectangle bounds = device.getDefaultConfiguration().getBounds();
                    ScreenShotMainWindow screenShotWindow = new ScreenShotMainWindow(bounds);
                    screenShotWindow.setVisible(true);
                    screenShotWindow.toFront();
                    screenShotWindows.add(screenShotWindow);
                }
                boolean isConfirm = false;
                while (!isConfirm) {
                    Thread.sleep(100);
                    for (ScreenShotMainWindow screenShotWindow : screenShotWindows) {
                        if (screenShotWindow.isVisible()) {
                            continue;
                        }
                        isConfirm = true;
                        if (screenShotWindow.getImage() == null) {
                            imageLabel.setIcon(null);
                            screenShotWindow.dispose();
                            break;
                        }
                        imageLabel.setIcon(new ImageIcon(screenShotWindow.getImage()));
                        screenShotWindow.dispose();
                        break;
                    }
                }
                for (ScreenShotMainWindow screenShotWindow : screenShotWindows) {
                    screenShotWindow.setVisible(false);
                    screenShotWindow.dispose();
                }
                if (autoOcrCheckBox.isSelected()) {
                    imageOcr(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.error(e.getMessage());
                AppUiMain.errorMsgBox(e.getMessage());
            } finally {
                if (trayRun && imageLabel.getIcon() == null) {
                    // 托盘运行且不需要截图识别，则不显示程序界面
                    return;
                }
                AppUiMain.showAppUi(1);
            }
        });
    }

    /**
     * 识别
     *
     * @return
     * @author guochaohui
     * @date 2020-04-01 16:53
     */
    private static void imageOcr(boolean auto) {
        if (imageLabel.getIcon() == null) {
            if (!auto) {
                AppUiMain.errorMsgBox("没有截图，无法识别");
            }
            return;
        }
        AppUiMain.showLoading("文字识别中，请稍候......");
        AppThreadUtil.INSTANCE.getExecutor().submit(() -> {
            try {
                ImageIcon imageIcon = (ImageIcon) imageLabel.getIcon();
                BufferedImage image = (BufferedImage) imageIcon.getImage();
                OcrService ocrService = (OcrService) ocrServiceTypeComboBox.getModel().getSelectedItem();
                List<String> results = CoreBusiness.doImageOcr(image, ocrService);
                ocrText.setText(Joiner.on("\r\n").join(results));
            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.error(e.getMessage());
                AppUiMain.errorMsgBox(e.getMessage());
            } finally {
                AppUiMain.hideLoading();
            }
        });
    }

}
